/*
 * @Author: ylq
 * @Date: 2021-08-24 16:58:33
 * @Desc: 工具箱
 * @Last Modified by: ylq
 * @Last Modified time: 2023-12-12 14:27:18
 */
class Tools {
  constructor() {}
  // 设置cookie
  setCookie(name, value, t, domain) {
    var days = (t === undefined ? 1 : t) * 24 * 60 * 60 * 1000;
    var hostname = window.location.hostname;
    var d = domain || (hostname.indexOf('xiaolutg.com') > -1 ? 'xiaolutg.com' : hostname);
    var exp = new Date();
    exp.setTime(exp.getTime() + days);
    console.log(15, exp.toGMTString());
    document.cookie = `${name}=${escape(value)};path=/;domain=${d};expires=${exp.toGMTString()}`;
  }
  // 获取cookie
  getCookie(key) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split(';');
    for (var m = 0; m < arrCookie.length; m++) {
      var ac = arrCookie[m].replace(/\s*/g, '');
      if (ac.indexOf(key + '=') != -1) {
        return ac.replace(key + '=', '');
      }
    }
  }
  // 生成随机6位字符串
  randomString(len) {
    len = len || 6;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  // 数组生成树
  arrayToTree(arr = [], pid = 0, props = { children: 'children', id: 'id', pid: 'pid' }) {
    const p = props;
    const list = [];
    const obj = {};
    arr.forEach((el) => {
      obj[el[p.id]] = el;
      if (el[p.pid] === pid) {
        list.push({ ...el, children: this.arrayToTree(arr, el[p.id]).tree });
      }
    });
    return { obj, tree: list };
  }

  // 根据传入的2个时间，计算间隔天数，计算每个日期数量，计算环比日期
  //  st 开始时间，et,结束时间，hasOqo 是否有环比日期 hasToday是否包含今天
  getDateTotal(st, et, hasOqo = false, hasToday) {
    console.log(6900001111, st, et, hasOqo, hasToday);
    const defst = st ? new Date(st) : new Date();
    const defet = et ? new Date(et) : new Date();
    console.log(690000, defst, defet);
    const oneDay = 24 * 60 * 60 * 1000;
    let start = defst;
    let end = defet;
    if (defst.getTime() > defet.getTime()) {
      start = defet;
      end = defst;
    }
    console.log(690001, start, end);
    // 获取毫秒
    const times = end.getTime() - start.getTime();
    // 获取天数
    const dayNum = parseInt(times / oneDay);
    // 获取年月日
    const getYmd = (ymd) => {
      const date = new Date(ymd);
      const gm = date.getMonth() + 1;
      const m = gm < 10 ? `0${gm}` : gm;
      const d = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
      return `${date.getFullYear()}-${m}-${d}`;
    };
    // 获取区间
    const getAreaDate = (n, s) => {
      const arr = [];
      const arrDate = [];
      const arrWeek = [];
      const date = [];
      for (let index = 0; index < n; index++) {
        let t = s.getTime() + index * oneDay;
        if (hasToday === false) {
          t = s.getTime() + index * oneDay - oneDay;
        }
        arr.push(t);
        arrDate.push(getYmd(t));
        arrWeek.push(new Date(t).getDay());
        if (index === 0) {
          date.push(getYmd(t));
        }
        if (index === n - 1) {
          console.log(6900023101, index, n - 1, getYmd(t));
          date.push(getYmd(t));
        }
      }
      return { arr, arrDate, arrWeek, date };
    };
    // 如果需要环比日期
    console.log(hasOqo);
    let oqoArea = {};
    if (hasOqo) {
      const oqoDayNum = dayNum + 1;
      const oqoStart = start.getTime() - oqoDayNum * oneDay;
      // const oqoEnd = start.getTime() - oneDay ;
      console.log(6900023, oqoStart);
      oqoArea = getAreaDate(oqoDayNum, new Date(oqoStart));
      // oqoArea.date = [getYmd(oqoStart),getYmd(oqoEnd)]
    }
    // 获取所有的数据 天数，周，日期秒，日期
    const area = getAreaDate(dayNum + 1, start);
    const o = {
      num: dayNum,
      week: area.arrWeek,
      date: area.date,
      dateArea: area.arrDate,
      dateAreaMs: area.arr,
      oqoArea: oqoArea.arrDate,
      oqoAreaMs: oqoArea.arr,
      oqoDate: oqoArea.date,
      oqoAreaWeek: oqoArea.arrWeek
    };
    // 如果只传了1天时间
    if (start.getTime() === end.getTime()) {
      const d = [getYmd(start), getYmd(end)];
      o.num = 0;
      o.week = start.getDay();
      o.date = d;
      o.dateArea = d;
      o.dateAreaMs = [start.getTime(), start.getTime()];
      if (hasOqo) {
        const yesterday = start.getTime() - oneDay;
        o.oqoArea = [getYmd(yesterday), getYmd(yesterday)];
        o.oqoAreaMs = [yesterday, yesterday];
        o.oqoDate = [getYmd(yesterday), getYmd(yesterday)];
        o.oqoAreaWeek = new Date(yesterday).getDay();
      }
    }
    return o;
  }
  // 清除区号+86
  clearCountryNum(num) {
    if (!num) return;
    let n = num;
    if (num.indexOf('+86') === 0) {
      n = num.replace('+86', '');
      n = n.trim();
    }
    return n;
  }
  // 下载方法
  downLoad(res, name) {
    // 获取模板
    const link = document.createElement('a');
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
    const url = window.URL || window.webkitURL || window.moxURL;
    link.href = url.createObjectURL(blob);
    link.download = name + '.xlsx';
    link.click();
    window.URL.revokeObjectURL(url);
  }
  //获取用户浏览器信息
  getWindowNavigator() {
    let ratio = 0;
    if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
      //获取浏览器窗口外部的宽度,可视区域的宽度
      ratio = window.outerWidth / window.innerWidth;
    }
    if (ratio) {
      ratio = Math.round(ratio * 100);
    }
    const navigator = window.navigator; //浏览器navigator对象
    const navigatorObject = {
      appName: navigator.appName, //浏览器的官方名称
      appVersion: navigator.appVersion, //浏览器的平台和版本信息
      platform: navigator.platform, //浏览器运行的操作系统平台
      userAgent: navigator.userAgent, //浏览器的厂商和版本信息，即浏览器运行的操作系统、浏览器的版本、名称
      screenWidth: window.screen.width, //浏览器分辨率宽
      screenHeight: window.screen.height, //浏览器分辨率高
      zoomRatio: ratio
    };
    return navigatorObject;
  }

  //markdown转文本
  stripMarkdown(text) {
    // 匹配Markdown标题标签
    text = text.replace(/#+\s/g, '');
    // 匹配Markdown加粗标签
    text = text.replace(/\*\*(.*?)\*\*/g, '$1');
    // 匹配Markdown斜体标签
    text = text.replace(/\*(.*?)\*/g, '$1');
    // 匹配Markdown图片标签
    text = text.replace(/!\[(.*?)\]\((.*?)\)/g, '');
    // 匹配Markdown链接标签
    text = text.replace(/\[(.*?)\]\((.*?)\)/g, '$1 ($2)');
    // 匹配Markdown代码块标签
    text = text.replace(/```(.*?)\n(.*?)```/gs, '$2');
    // 匹配Markdown内联代码标签
    text = text.replace(/`([^`]+)`/g, '$1');
    // 返回纯文本
    return text.trim();
  }

  //通过子ID获取父级及以上的ID，直到最顶级
  getTreeDeepArr(key, treeData, idKey, idLabel, childKey) {
    // console.log(key, treeData, idKey, idLabel, childKey);
    idKey = idKey || 'value';
    idLabel = idLabel || 'label';
    childKey = childKey || 'children';
    // console.log(key, treeData, idKey, childKey);
    const arr = []; // 在递归时操作的数组
    const arrLabel = []; // 在递归时操作的数组
    let returnArr = []; // 存放结果的数组
    let depth = 0; // 定义全局层级
    // 定义递归函数
    function childrenEach(childrenData, depthN) {
      for (var j = 0; j < childrenData.length; j++) {
        depth = depthN; // 将执行的层级赋值 到 全局层级
        arr[depthN] = childrenData[j][idKey];
        arrLabel[depthN] = childrenData[j][idLabel];
        if (childrenData[j][idKey] == key) {
          returnArr = {
            iVal: arr.slice(0, depthN + 1),
            iLabel: arrLabel.slice(0, depthN + 1)
            // jobGroup: childrenData[j][childKey]
          };
          //将目前匹配的数组，截断并保存到结果数组，
          break;
        } else {
          if (childrenData[j][childKey]) {
            depth++;
            childrenEach(childrenData[j][childKey], depth);
          }
        }
      }
      return returnArr;
    }
    return childrenEach(treeData, depth);
  }
  setPrice(price, num) {
    // num必须是数字类型
    if (!price && isNaN(price)) return price;
    const number = num === undefined ? 2 : num === 0 ? 0 : num;
    return parseFloat(parseFloat(price * 10000).toFixed(number));
  }
  getPrice(price, num) {
    if (!price && isNaN(price)) return price;
    const number = num == undefined ? 2 : num === 0 ? 0 : num;
    return parseFloat(parseFloat(price / 10000).toFixed(number));
  }
  getPriceSetting(price) {
    const prices = ['万', '亿'];
    let num = parseFloat(price);
    for (let i = 0; i < prices.length; i++) {
      if (num >= 10000) {
        num /= 10000;
        price = num.toFixed(1) + prices[i];
      } else if (num >= 1000000 && i < prices.length - 1) {
        num /= 1000000;
        price = num.toFixed(1) + prices[i + 1];
      } else {
        break;
      }
    }
    return price;
  }
  // 检查是否是标准的JSON字符串
  isJSON(str) {
    if (typeof str === 'string') {
      try {
        var obj = JSON.parse(str);
        return !!(typeof obj === 'object' && obj);
      } catch (e) {
        return false;
      }
    }
    return false;
  }
}

export const tools = new Tools();
